import { Table, Input, InputNumber, Popconfirm, Form, Button, Icon, Divider } from 'antd';
import React, { Component } from 'react';
import {connect} from 'dva'

const MyLabel = (props) => (
  <>
  <span><span style={{color: 'red'}}>*</span>{props.name}</span>
  </>
)

interface IContextProps {
  state: any;
  dispatch: ({ type }: { type: string }) => void;
}

const EditableContext = React.createContext({} as IContextProps);
class EditableCell extends Component<any, any> {
  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `请输入 ${title.props.name}!`,
                },
              ],
              initialValue: record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}
@connect(({micro}) => ({
	details: micro.details || {},

}))
class EditableTable extends Component<any> {
  state = { 
    editingKey: '' ,
    isDisable: false,
    dataSource: [
      // {
      //   key: '站长',
      //   name: '',
      //   age: '',
      //   kind: '站长',
      //   gender: '',
      //   mobile: '',
      // },
      // {
      //   key: '消防员1',
      //   name: '',
      //   age: '',
      //   kind: '消防员',
      //   gender: '',
      //   mobile: '',
      // },
      // {
      //   key: '消防员2',
      //   name: '',
      //   age: '',
      //   kind: '消防员',
      //   gender: '',
      //   mobile: '',
      // },
    ],
    count: 2,
  
  };
  remove = (key) => {
    const { dispatch } = this.props

    let arr =this.state.dataSource;
    let res = arr.filter((item) => +item.key !== +key)
    dispatch({ type: 'micro/collectData', payload: res})
    this.setState({dataSource: res})
  }
  componentDidMount() {
    const { dispatch } = this.props
    dispatch({type: 'micro/queryInfo'}).then(() => {
      const {  details } = this.props
      const res = details && Array.isArray(details.member) && (details.member).map((item, ind) => ({
         key: ind,
        ...item
      }))
      dispatch({ type: 'micro/collectData', payload: [...res]})

      this.setState({ dataSource: [...this.state.dataSource, ...res ] })
    })
  }
  constructor(props) {
    super(props);
    
  }



  columns = [
    {
      title: '成员',
      dataIndex: 'kind',
      render: (text, record, index) => 
       (+index === 0 ? <MyLabel name={record.kind}/> : record.kind)
      
    },
    {
      title:  <MyLabel name="姓名"/>,
      dataIndex: 'name',
      editable: true,
    },
    {
      title: <MyLabel name="性别"/>,
      dataIndex: 'gender',
      editable: true,
    },
    {
      title: <MyLabel name="年龄"/>,
      dataIndex: 'age',
      editable: true,
    },
    {
      title: <MyLabel name="联系方式"/>,
      dataIndex: 'mobile',
      editable: true,
    },

    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        const { editingKey } = this.state;
        const editable = this.isEditing(record);
        return editable ? (
          <span>
            <EditableContext.Consumer>
              {form => (
                <a
                  onClick={() => this.save(form, record.key)}
                  style={{ marginRight: 8 }}
                >
                  保存
                </a>
              )}
            </EditableContext.Consumer>
            <Popconfirm title="确定取消?" onConfirm={() => this.cancel(record.key)}>
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <>
          <a disabled={editingKey !== ''} onClick={() => this.edit(record.key)}>
            编辑
            <Divider style={{marginTop: -10}} type="vertical" />

          </a>
          
            <Popconfirm
              title="请确认是否删除?"
              onConfirm={() => this.remove(record.key)} okText="确定" cancelText="取消"
            >
              
                <a style={{marginLeft: 20}} disabled={record.key === 0 || record.key === 1 || record.key === 2 } >
                  删除
                </a>
            </Popconfirm>
         
          </>
        );
      },
    },
  ];

  isEditing = record => record.key === this.state.editingKey;

  cancel = () => {
    this.setState({ 
      dataSource: this.props.details.member,
      isDisable: false
    });
  };
 //收集表格数据
  save(form, key) {
    const { dispatch } = this.props
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.dataSource];
      const index = newData.findIndex(item => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        this.setState({ dataSource: newData, editingKey: '', isDisable: false }, () => {
          dispatch({ type: 'micro/collectData', payload: this.state.dataSource})
          if(this.state.dataSource.length > 9 ){
            this.setState({isDisable: true})
          }
        });
      } else {
        newData.push(row);
        this.setState({ dataSource: newData, editingKey: '', isDisable: false }), () => {
          dispatch({ type: 'micro/collectData', payload: this.state.dataSource})
          if(this.state.dataSource.length > 9 ){
            this.setState({isDisable: true})
          }
        };
      }
    });
  }

  edit(key) {
    this.setState({ editingKey: key });
  }
  handleAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
      key: Date(),
      name: '',
      age: '',
      kind: '消防员',
      gender: '',
      mobile: '',
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    }, () =>{
      this.edit(newData.key)
      this.setState({isDisable: true})
    
    });
   
  };

  render() {
    
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <>
      <EditableContext.Provider value={this.props.form}>
        <Table
          components={components}
          bordered
          dataSource={this.state.dataSource}
          columns={columns}
          pagination={false}
        />
        <Button disabled={ ( this.state.isDisable  ) ? true : false } onClick={this.handleAdd} type="primary" style={{ marginBottom: 16, width: '100%', backgroundColor: '#fff', color: 'rgba(8,128,223,1)', border: '1px dashed rgba(8,128,223,1)' }}>
        <Icon type="plus" />
          新增成员 
        </Button>
      </EditableContext.Provider>
      </>
    );
  }
}

const EditableFormTable = Form.create()(EditableTable);

export default EditableFormTable
